use serde_json::value::Value;
use std::convert::AsRef;
use std::path::{Path, PathBuf};

pub fn new(config_file_name: Option<&str>) -> Value {
  fn fine_file_name_for_test(path: PathBuf) -> PathBuf {
    let file_name = path
      .file_name()
      .map_or("", |x| x.to_str().unwrap_or_default());
    if file_name.contains('-') {
      let file_name = file_name.split('-').next().unwrap_or_default();
      PathBuf::from(file_name)
    } else {
      path
    }
  }
  let path = if let Some(file_name) = config_file_name {
    PathBuf::from(file_name)
  } else {
    let path = std::env::current_exe().unwrap();
    let mut path = fine_file_name_for_test(path);
    path.set_extension("json");
    path
  };
  let path = if !path.exists() {
    let file_name = path.file_name().unwrap_or_default();
    PathBuf::from(file_name)
  } else {
    path
  };
  if !path.exists() {
    panic!("Application config file: {:?} does not exist!", path);
  }
  read_json(path)
}
fn read_json<P: AsRef<Path>>(path: P) -> Value {
  if let Ok(file) = std::fs::File::open(path) {
    let reader = std::io::BufReader::new(file);
    if let Ok(value) = serde_json::from_reader(reader) {
      value
    } else {
      Value::Null
    }
  } else {
    Value::Null
  }
}

/* #[cfg(test)]
mod tests {
    use serde_json::json;
    #[test]
    fn test_config_new() {
        let config = super::new();
        assert_eq!(
            config["config"],
            json!({
                "static_path": "D:/Js/OnlyOne/public",
                "server_name": "OnlyOne",
                "http_active": true,
                "http_port": 80,
                "https_active": true,
                "https_port": 443,
                "https_cert": "cert.pem",
                "https_key": "key.pem"
            })
        );
        assert_eq!(config["config"]["https_port"], json!(443));
    }
}
 */
